package com.yami.shop.api.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.UserCollectionDto;
import com.yami.shop.bean.dto.UserCollectionDtcDto;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.event.SendPersonMessageEvent;
import com.yami.shop.bean.model.Blog;
import com.yami.shop.bean.model.Comment;
import com.yami.shop.bean.model.NotifyLog;
import com.yami.shop.bean.model.UserCollectionDtc;
import com.yami.shop.bean.param.NotifyTemplateParam;
import com.yami.shop.bean.vo.UserCollectionDtcVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.BlogService;
import com.yami.shop.service.CommentService;
import com.yami.shop.service.NotifyLogService;
import com.yami.shop.service.UserCollectionDtcService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/p/user/collectionDtc")
@Tag(name = "新收藏接口")
@AllArgsConstructor
public class UserCollectionDtcController {

    private final UserCollectionDtcService userCollectionDtcService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private CommentService commentService;
    @Autowired
    private NotifyLogService notifyLogService;
    @Autowired
    private BlogService blogService;
    @GetMapping("/pagePersonnft")
    @Operation(summary =  "分页返回藏品收藏数据", description = "根据用户id获取")
    public ServerResponseEntity<IPage<UserCollectionDto>> pagePersonnft(PageParam page) {
        String userId = SecurityUtils.getUser().getUserId();
//        userCollectionDtcService.page(page,)
        return ServerResponseEntity.success();
    }
    @GetMapping("/pageBlog")
    @Operation(summary =  "分页返回博文收藏数据", description = "根据用户id获取")
    public ServerResponseEntity<IPage<UserCollectionDtcVO>> pageBlog(PageParam page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<UserCollectionDtcVO> iPage = userCollectionDtcService.pageBlog(page, userId);
        //判断是否点赞过
        List<Long> blogIds = iPage.getRecords().stream().map(UserCollectionDtcVO::getProdId).collect(Collectors.toList());
        List<Long> fanalBlogIds = null;
        if(blogIds.size()>0){
            QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("blog_uid", blogIds);
            queryWrapper.eq("source", "1");
            queryWrapper.eq("user_uid",userId);
            queryWrapper.isNull("to_uid");
            queryWrapper.eq("type",1);
            queryWrapper.eq("status", 1);
            // 查询出该文章下所有的评论
            List<Comment> pageList = commentService.list(queryWrapper);
            fanalBlogIds = pageList.stream().map(Comment::getBlogUid).collect(Collectors.toList());
        }
        List<Long> finalFanalBlogIds = fanalBlogIds;
        if(finalFanalBlogIds!=null && finalFanalBlogIds.size()>0){
            iPage.getRecords().forEach(userCollectionDtcVO ->{
                    //判断是否点赞过
                userCollectionDtcVO.setPraiseIsMe(finalFanalBlogIds.contains(userCollectionDtcVO.getProdId())?true:false);
            });
        }

        return ServerResponseEntity.success(iPage);
    }
    @GetMapping("/pageShowroom")
    @Operation(summary =  "分页返回展馆收藏数据", description = "根据用户id获取")
    public ServerResponseEntity<IPage<UserCollectionDto>> pageShowroom(PageParam page) {
        String userId = SecurityUtils.getUser().getUserId();
//        userCollectionDtcService.page(page,)
        return ServerResponseEntity.success();
    }
    @PostMapping("/addOrCancel")
    @Operation(summary =  "保存/取消", description = "收藏")
    public ServerResponseEntity getUserCollectionDtoPageByUserId(@RequestBody UserCollectionDtcDto userCollectionDtcDto) {
        String userId = SecurityUtils.getUser().getUserId();
        LambdaQueryWrapper<UserCollectionDtc> eq = new LambdaQueryWrapper<UserCollectionDtc>()
                .eq(UserCollectionDtc::getUserId, userId)
                .eq(UserCollectionDtc::getCollectionType, userCollectionDtcDto.getCollectionType())
                .eq(UserCollectionDtc::getProdId, userCollectionDtcDto.getProdId());
        if("2".equals(userCollectionDtcDto.getType())){
            //取消
            userCollectionDtcService.remove(eq);
        }else{
            //收藏
            long count = userCollectionDtcService.count(eq);
            //检验是否收藏过博客对应圈子或者圈子对应博客
            if(count==0&&userCollectionDtcDto.getCollectionType().equals("2")){
                Blog blog = blogService.getById(userCollectionDtcDto.getProdId());
                if(blog.getStatus()!=1){
                    return ServerResponseEntity.showFailMsg("已经下架不能收藏");
                }
                LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
                blogLambdaQueryWrapper.eq(Blog::getStatus,1);//审核通过
                blogLambdaQueryWrapper.eq(Blog::getTitle,blog.getTitle());
                List<Blog> list = blogService.list(blogLambdaQueryWrapper);
                List<Long> collect = list.stream().map(Blog::getUid).collect(Collectors.toList());
                LambdaQueryWrapper<UserCollectionDtc> eq1 = new LambdaQueryWrapper<UserCollectionDtc>()
                        .eq(UserCollectionDtc::getUserId, userId)
                        .eq(UserCollectionDtc::getCollectionType, userCollectionDtcDto.getCollectionType())
                        .in(UserCollectionDtc::getProdId, collect);
                long count1 = userCollectionDtcService.count(eq1);
                if(count1>0){
                    //删除 另一个消息
                    LambdaQueryWrapper<NotifyLog> wrapper3 = new LambdaQueryWrapper<>();
                    wrapper3.in(NotifyLog::getBlogId, collect);
                    wrapper3.eq(NotifyLog::getType,3);
                    wrapper3.eq(NotifyLog::getUserId,userId);
                    List<NotifyLog> list3 = notifyLogService.list(wrapper3);
                    if(list3.size()>0){
                        //评论和点赞集合合并
                        list3.forEach(item -> {
                            item.setStatus(-1);
                        });
                        notifyLogService.updateBatchById(list3);
                    }
                    //删除 另一个收藏
                    userCollectionDtcService.remove(eq1);
                }
            }
            if(count==0){
                UserCollectionDtc userCollectionDtc = new UserCollectionDtc();
                userCollectionDtc.setCollectionType(userCollectionDtcDto.getCollectionType());
                userCollectionDtc.setUserId(userId);
                userCollectionDtc.setChannelCode(userCollectionDtcDto.getChannelCode());
                userCollectionDtc.setProdId(userCollectionDtcDto.getProdId());
                userCollectionDtc.setCreateTime(new Date());
                userCollectionDtcService.save(userCollectionDtc);
                // 发送用户消息
                NotifyTemplateParam shopParam = new NotifyTemplateParam();
                shopParam.setShopId(Constant.PLATFORM_SHOP_ID);
                shopParam.setSendType(SendType.COLLECTION_REMINDER.getValue());
                //动态
                if(userCollectionDtcDto.getCollectionType().equals("2")){
                    shopParam.setToTypeName("动态");
                    Blog blog = blogService.getById(userCollectionDtcDto.getProdId());
                    if(blog.getArticleSource()==1){//目前只发用户
                        shopParam.setUserId(blog.getUserUid());
                        shopParam.setFromUserId(userId);
                        shopParam.setBlogId(userCollectionDtcDto.getProdId().toString());
                        shopParam.setType(3);
                        applicationContext.publishEvent(new SendPersonMessageEvent(shopParam));
                    }
                }else if(userCollectionDtcDto.getCollectionType().equals("1")){  //商品
                    shopParam.setToTypeName("商品");
                    // DOTO shopParam.setUserId(blog.getUserUid());
                }else if(userCollectionDtcDto.getCollectionType().equals("3")){//展厅
                    shopParam.setToTypeName("展厅");
                    // DOTO shopParam.setUserId(blog.getUserUid());
                }
            }
        }
        return ServerResponseEntity.success();
    }


    @GetMapping("/isCollection")
    @Operation(summary =  "根据商品id获取该商品是否在收藏夹中", description = "传入收藏商品id")
    @Parameter(name = "prodId", description = "商品id", required = true)
    public ServerResponseEntity<Boolean> isCollection(String prodId) {
        return ServerResponseEntity.success();
    }


    @GetMapping("/count")
    @Operation(summary =  "查询用户收藏商品数量", description = "查询用户收藏商品数量 collectionType==null 代表全部")
    public Long findProdCollectionCount(String collectionType) {
        String userId = SecurityUtils.getUser().getUserId();
        if(StrUtil.isNotEmpty(collectionType)){
            return userCollectionDtcService.count(new LambdaQueryWrapper<UserCollectionDtc>().eq(UserCollectionDtc::getUserId, userId).eq(UserCollectionDtc::getCollectionType, collectionType));
        }
        return userCollectionDtcService.count(new LambdaQueryWrapper<UserCollectionDtc>().eq(UserCollectionDtc::getUserId, userId));
    }

}
